import flet as ft
import json
import os.path

from flet_core import FilePicker

from utils import snack_bar, mkdir
from PIL import Image

from views.treasure_dialogs.baseDialog import BaseDialog2

"""
图片文件大小修改
"""


class ImgDialog(BaseDialog2):
    def __init__(self, page: ft.Page):
        self.page = page
        self.choose_file_dialog = None
        # 创建关闭按钮
        self.close_btn = ft.IconButton(
            icon=ft.icons.CLOSE_OUTLINED,
            on_click=self.close_dlg
        )

        # 创建选择文件按钮
        self.choose_file_btn = ft.FloatingActionButton(
            "选择文件",
            on_click=self.show_file_picker,
            width=300
        )

        self.x_input = ft.TextField(label="X 输入")
        self.y_input = ft.TextField(label="Y 输入")

        row = ft.Row(
            controls=[self.x_input, self.y_input],
            alignment=ft.MainAxisAlignment.CENTER  # 水平居中
        )
        column = ft.Column([self.choose_file_btn])
        # 使用 Column 控件将 Row 和 Column 垂直堆叠
        self.content = ft.Column(controls=[row, column])

        # 创建底层对话框的内容
        self.base_content = ft.Column(controls=[row, column],
                                      alignment=ft.MainAxisAlignment.CENTER,  # 垂直居中
                                      horizontal_alignment=ft.CrossAxisAlignment.CENTER  # 水平居中
                                      )

        # 创建底层对话框
        self.base_dialog = ft.Container(
            content=ft.Card(
                content=ft.Column([
                    ft.Row([
                        ft.Text("图片大小转换"),
                        self.close_btn  # 关闭按钮放在右上角
                    ], alignment=ft.MainAxisAlignment.SPACE_BETWEEN),
                    self.base_content
                ]),
                elevation=10,
                margin=ft.margin.all(20),
            ),
            visible=True,  # 底层对话框默认可见
            height=self.page.window_height * 0.8,  # 设置高度为页面高度的 80%
            width=self.page.window_width,  # 可选：设置宽度为页面宽度
            alignment=ft.alignment.center  # 将内容居中对齐
        )

        # 创建图片预览对话框
        self.prompt_dialog = ft.Container(
            content=ft.Card(
                content=ft.Column([
                    ft.Text("图片预览"),
                    ft.Image(
                        src="",  # 初始为空
                        fit=ft.ImageFit.CONTAIN  # 图片适应控件大小
                    ),
                    ft.Row([ft.TextButton("关闭", on_click=lambda e: self.hide_prompt(e))],
                           alignment=ft.MainAxisAlignment.CENTER)
                ]),
                elevation=10,
                margin=ft.margin.all(20),
            ),
            visible=False  # 预览对话框初始不可见
        )
        # 使用Stack来堆叠两个对话框
        self.stack = ft.Stack(controls=[self.base_dialog, self.prompt_dialog])

        # 文件选择器
        self.file_picker = FilePicker(on_result=self.on_file_picker_result)
        self.page.overlay.append(self.file_picker)
        self.page.update()

    def show_file_picker(self, e):
        # 显示文件选择器
        self.file_picker.pick_files(allowed_extensions=['jpg', 'jpeg', 'png'])

    def open_dialog(self, e):
        if self.choose_file_dialog is None:
            self.choose_file_dialog = ft.FilePicker(on_result=self.upload_action)
            self.page.overlay.append(self.choose_file_dialog)
            self.page.update()
        self.choose_file_dialog.pick_files(dialog_title="选择图片", file_type="any")

    def on_file_picker_result(self, e: ft.FilePickerResultEvent):
        if e.files:
            for file in e.files:
                # 显示图片预览
                data = json.loads(e.data)
                self.file_path = data["files"][0]["path"]
                print(self.file_path)

                # 动态设置图片的 src 属性
                self.prompt_dialog.content.content.controls[1].src = self.file_path  # 更新预览对话框中的图片

                # 移除现有的图片控件、文本控件和按钮（如果存在）
                if hasattr(self, 'imageBefor'):
                    self.base_content.controls.remove(self.image)
                if hasattr(self, 'size_befor'):
                    self.base_content.controls.remove(self.size_text)
                if hasattr(self, 'imageAfter'):
                    self.base_content.controls.remove(self.image)
                if hasattr(self, 'size_after'):
                    self.base_content.controls.remove(self.size_text)
                if hasattr(self, 'setting_img_btn'):
                    self.base_content.controls.remove(self.setting_img_btn)
                # 这里可以上传文件
                # file_picker.upload(file, upload_url, method="PUT")
                # 创建一个 Image 控件，用于显示原始图片
                # 使用 GestureDetector 来包裹 Image 控件，以便监听点击事件
                self.imageBefor = ft.GestureDetector(
                    on_double_tap=self.show_prompt,
                    content=ft.Image(src=self.file_path, width=200, height=200)
                )
                # 创建一个 Image 控件，用于预留显示处理后的图片
                self.imageAfter = ft.Image(src="aaa.jpg", width=200, height=200,
                                           error_content=ft.Text("处理后显示", color=ft.colors.RED))
                # 将图片控件添加到列布局中
                row1 = ft.Row(controls=[self.imageBefor, self.imageAfter],
                              alignment=ft.MainAxisAlignment.CENTER  # 水平居中
                              )
                file_size = os.path.getsize(self.file_path)
                self.size_befor = ft.Text(f'处理前：{file_size}字节')
                self.size_after = ft.Text(f'处理后：「」字节')
                row2 = ft.Row(controls=[self.size_befor, self.size_after],
                              alignment=ft.MainAxisAlignment.CENTER  # 水平居中
                              )
                self.setting_img_btn = ft.ElevatedButton("处理", on_click=self.setting_img, width=300)

                # 将新控件添加到底层对话框的内容中
                self.base_content.controls.append(row1)
                self.base_content.controls.append(row2)
                self.base_content.controls.append(self.setting_img_btn)
                # 更新页面以显示新控件
                self.page.update()

    # 修改图片大小
    async def setting_img(self, file_path):
        if not self.x_input.value:
            snack_bar(self.page, "x_value 不能为空")
            return  # 提前返回，不再执行后续代码
        else:
            x_value = int(self.x_input.value)
        if not self.y_input.value:
            snack_bar(self.page, "y_value 不能为空")
            return  # 提前返回，不再执行后续代码
        else:
            y_value = int(self.y_input.value)
        print(self.file_path)
        path = str(self.file_path)
        old_img = Image.open(path)
        img_deal = old_img.resize((x_value, y_value), Image.LANCZOS)
        img_deal = img_deal.convert('RGB')
        pure_path = os.path.dirname(path)
        print(pure_path)
        file_name = os.path.basename(path)
        print(file_name)
        new_file_dir = pure_path + '/new_img/'
        mkdir(new_file_dir)
        new_file_name = new_file_dir + 'switch_' + file_name
        print(new_file_name)
        if os.path.isfile(new_file_name):
            print(new_file_name, '文件已存在,将其删除')
            os.remove(new_file_name)
            img_deal.save(new_file_name)
        else:
            img_deal.save(new_file_name)
        self.imageAfter.src = new_file_name
        file_size = os.path.getsize(new_file_name)
        self.size_after.value = f'处理后：{file_size}字节'
        snack_bar(self.page, f"转换完成，已保存")
